<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

interface MedicalRecord {
  id: number
  patient_id: number
  patientName: string
  type: string
  date: string
  doctor: string
  status: string
  notes: string
  created_at?: string
  updated_at?: string
}

const records = ref<MedicalRecord[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const isEdit = ref(false)
const currentRecord = ref<MedicalRecord | null>(null)

const formData = ref({
  patientId: '',
  type: '',
  date: '',
  doctor: '',
  status: '待处理',
  notes: ''
})

const rules = {
  patientId: [{ required: true, message: '请选择患者', trigger: 'change' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  doctor: [{ required: true, message: '请输入医生姓名', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// Fetch medical records from API
const fetchRecords = async () => {
  try {
    loading.value = true
    const response = await axios.get('http://localhost:3000/api/medical')
    const data = response.data
    records.value = Array.isArray(data) ? data : []
  } catch (error) {
    console.error('获取医疗记录失败:', error.response?.data || error.message);
    ElMessage.error('获取医疗记录失败')
    records.value = []
  } finally {
    loading.value = false
  }
}

// Add new medical record
const addRecord = async () => {
  try {
    // 验证患者ID是否为数字
    const patientId = parseInt(formData.value.patientId);
    if (isNaN(patientId)) {
      ElMessage.error('患者ID必须是有效的数字');
      return;
    }

    // 验证必填字段
    if (!formData.value.type || !formData.value.date || !formData.value.doctor || !formData.value.status) {
      ElMessage.error('请填写所有必填字段');
      return;
    }

    const data = {
      patient_id: patientId,
      type: formData.value.type,
      date: formData.value.date,
      doctor: formData.value.doctor,
      status: formData.value.status,
      notes: formData.value.notes || ''
    };

    console.log('发送的数据:', data);

    const response = await axios.post('http://localhost:3000/api/medical', data);
    
    if (response.data) {
      ElMessage.success('添加记录成功');
      dialogVisible.value = false;
      await fetchRecords();
      resetForm();
    }
  } catch (error) {
    console.error('添加记录失败:', error.response?.data || error.message);
    ElMessage.error(error.response?.data?.error || '添加记录失败');
  }
}

// Edit medical record
const editRecord = async () => {
  if (!currentRecord.value?.id) {
    ElMessage.error('无效的记录ID');
    return;
  }
  
  try {
    // 验证必填字段
    if (!formData.value.type || !formData.value.date || !formData.value.doctor || !formData.value.status) {
      ElMessage.error('请填写所有必填字段');
      return;
    }

    const data = {
      type: formData.value.type,
      date: formData.value.date,
      doctor: formData.value.doctor,
      status: formData.value.status,
      notes: formData.value.notes || ''
    };

    console.log('更新的数据:', {
      id: currentRecord.value.id,
      data: data
    });

    const response = await axios.put(`http://localhost:3000/api/medical/${currentRecord.value.id}`, data);
    
    if (response.data) {
      ElMessage.success('更新记录成功');
      dialogVisible.value = false;
      await fetchRecords();
      resetForm();
    }
  } catch (error) {
    console.error('更新记录失败:', error.response?.data || error.message);
    ElMessage.error(error.response?.data?.error || '更新记录失败');
  }
}

// Handle view details
const handleView = (row: MedicalRecord) => {
  currentRecord.value = row;
  detailDialogVisible.value = true;
}

// Handle edit button click
const handleEdit = (row: MedicalRecord) => {
  currentRecord.value = row;
  isEdit.value = true;
  formData.value = {
    patientId: row.patient_id.toString(),
    type: row.type || '',
    date: row.date || '',
    doctor: row.doctor || '',
    status: row.status || '待处理',
    notes: row.notes || ''
  };
  dialogVisible.value = true;
}

// Handle add button click
const handleAdd = () => {
  isEdit.value = false;
  currentRecord.value = null;
  resetForm();
  dialogVisible.value = true;
}

// Reset form
const resetForm = () => {
  formData.value = {
    patientId: '',
    type: '',
    date: '',
    doctor: '',
    status: '待处理',
    notes: ''
  };
}

onMounted(() => {
  fetchRecords();
});
</script>

<template>
  <div class="medical">
    <div class="header">
      <h2>医疗护理</h2>
      <el-button type="primary" @click="handleAdd">新增记录</el-button>
    </div>

    <el-table 
      :data="records" 
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="patientName" label="患者姓名" />
      <el-table-column prop="type" label="类型" />
      <el-table-column prop="date" label="日期" />
      <el-table-column prop="doctor" label="主治医生" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === '已完成' ? 'success' : row.status === '进行中' ? 'primary' : 'warning'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="notes" label="备注" show-overflow-tooltip />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleView(row)">查看</el-button>
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Add/Edit Medical Record Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑医疗记录' : '新增医疗记录'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="患者ID" prop="patientId">
          <el-input v-model="formData.patientId" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type" style="width: 100%">
            <el-option label="定期检查" value="定期检查" />
            <el-option label="用药提醒" value="用药提醒" />
            <el-option label="康复治疗" value="康复治疗" />
            <el-option label="专科诊断" value="专科诊断" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="formData.date"
            type="date"
            style="width: 100%"
            value-format="YYYY-MM-DD"
            :clearable="false"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="主治医生" prop="doctor">
          <el-input v-model="formData.doctor" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" style="width: 100%">
            <el-option label="待处理" value="待处理" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.notes"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="isEdit ? editRecord() : addRecord()">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- View Medical Record Details Dialog -->
    <el-dialog
      v-model="detailDialogVisible"
      title="医疗记录详情"
      width="500px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="患者姓名">
          {{ currentRecord?.patientName }}
        </el-descriptions-item>
        <el-descriptions-item label="类型">
          {{ currentRecord?.type }}
        </el-descriptions-item>
        <el-descriptions-item label="日期">
          {{ currentRecord?.date }}
        </el-descriptions-item>
        <el-descriptions-item label="主治医生">
          {{ currentRecord?.doctor }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentRecord?.status === '已完成' ? 'success' : currentRecord?.status === '进行中' ? 'primary' : 'warning'">
            {{ currentRecord?.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注">
          {{ currentRecord?.notes }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<style scoped>
.medical {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>